<template>
	<view class="search-result-list-container">
		<empty-data v-if="isEmpty"></empty-data>
		<mescroll-body v-else ref="mescrollRef" @init="mescrollInit" @down="downCallback" @up="upCallback">
			<!-- 循环渲染列表数据 -->
			<block v-for="(item, index) in resultList" :key="index">
				<view class="search-result-item-box" @click="onItemClick(item)">
					<search-result-item-theme-1 v-if="!item.pic_list || item.pic_list.length === 0" :data="item" />
					<search-result-item-theme-2 v-else-if="item.pic_list.length === 1" :data="item" />
					<search-result-item-theme-3 v-else :data="item" />
				</view>
			</block>
		</mescroll-body>
	</view>
</template>

<script>
	import MescrollMixin from '@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js';
	import {
		getSearchResult
	} from 'api/search';
	export default {
		mixins: [MescrollMixin],
		name: 'search-result-list',
		props: {
			// 搜索关键字
			queryStr: {
				type: String,
				required: true
			}
		},
		data() {
			return {
				// 数据源
				resultList: [],
				// 页数
				page: 1,
				// 当页面初次渲染时，不光会回调 init 方法，还回调 down、up方法，用来判断是否为首次请求
				isInit: true,
				mescroll: null,
				isEmpty: false
			};
		},
		// 页面渲染完成之后
		mounted() {
			this.mescroll = this.$refs.mescrollRef.mescroll
		},
		methods: {
			onItemClick(item) {
				uni.navigateTo({
					url: `/subpkg/pages/blog-detail/blog-detail?author=${item.author}&articleId=${item.id}`
				});
			},

			async mescrollInit() {
				await this.loadSearchResult();
				this.isInit = false
				this.mescroll.endSuccess()
				console.log("首次", this.isInit);
			},
			async downCallback() {
				if (this.isInit) return
				this.page = 1
				await this.loadSearchResult();
				this.mescroll.endSuccess()
			},
			async upCallback() {
				if (this.isInit) return
				this.page += 1
				await this.loadSearchResult();
				this.mescroll.endSuccess()
			},
			/**
			 * 获取搜索数据
			 */
			async loadSearchResult() {
				const {
					data: res
				} = await getSearchResult({
					q: this.queryStr,
					p: this.page
				});

				res.list.forEach((item) => {
					item.title = item.title.replace(/<em>/g, "<em style='color:#f94d2a; margin:0 2px'>");
					item.description = item.description.replace(
						/<em>/g,
						"<em style='color:#f94d2a; margin:0 2px'>"
					);
				});
				if (this.page === 1) {
					this.resultList = res.list;
				} else {
					this.resultList = [...this.resultList, ...res.list]
				}

				// 未查询到数据
				if (this.resultList.length === 0) {
					this.isEmpty = true;
				}
			}
		}
	};
</script>

<style lang="scss" scoped>
	.search-result-list-container {
		padding: $uni-spacing-col-lg $uni-spacing-row-lg;

		.search-result-item-box {
			margin-bottom: $uni-spacing-col-big;
		}
	}
</style>
